package com.xbongbong.saas.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.FormDataActiveRuleHelp;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DefaultTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.explain.FormDataAddFormExplainHandlerName;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.RelyPoJo;
import com.xbongbong.paas.help.FormDataValidateDataHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.ActiveRuleDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.dto.StartProcessDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.pojo.vo.FormDataAddGetVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.StartProcessVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.impl.base.BaseFormDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.explain.FormDataAddFormExplainHandlerName;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.permission.pojo.dto.VerifyAddPermissionDTO;
import com.xbongbong.process.operate.ProcessFieldHelp;
import com.xbongbong.process.operate.ProcessStartHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.help.DistributorAddHelp;
import com.xbongbong.saas.help.DistributorSaveHelp;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.ProDetailHandlerHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.service.DistributorFormDataService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.service.toolbox.help.SaasSaveHelper;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.help.ProPermissionHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 经销商档案
 *
 * @author xinpeng.jiang
 * @version 1.0
 * @date 2020/12/22 10:21
 * @since V1.0
 */
@Service("DistributorFormDataServiceImpl")
public class DistributorFormDataServiceImpl extends BaseFormDataService implements DistributorFormDataService {
    private static final Logger LOG = LoggerFactory.getLogger(DistributorFormDataServiceImpl.class);

    @Resource
    private DistributorAddHelp distributorAddHelp;
    @Resource
    private FormDataAddFormExplainHandlerName formDataAddFormExplainHandlerName;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProDetailHandlerHelp proDetailHandlerHelp;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private FormDataValidateDataHelp formDataValidateDataHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private SaasSaveHelper saasSaveHelper;
    @Resource
    private ProcessStartHelp processStartHelp;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private FormDataActiveRuleHelp formDataActiveRuleHelp;
    @Resource
    private ProModelService distributorProModelService;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private DistributorSaveHelp distributorSaveHelp;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private ProcessFieldHelp processFieldHelp;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private RichTextService richTextService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataAddGetVO addGet(FormDataAddGetDTO formDataAddGetDTO) throws XbbException {
        FormDataAddGetVO formDataAddGetVO = new FormDataAddGetVO();
        try {
            Integer businessType = formDataAddGetDTO.getBusinessType();
            //确认是否为创建回/付款单
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            Long formId = formDataAddGetDTO.getFormId();
            String corpid = formDataAddGetDTO.getCorpid();
            PaasFormEntityExt paasFormEntityExt;
            if (sheetFlag) {
                //预收款的formId是预收款余额的隐藏form，而非回款单的formId，因此要用businessType读取
                paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(sheetTypeEnum.getXbbRefTypeEnum().getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
                //置为回款单的formId
                formId = paasFormEntityExt.getId();
            } else {
                paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            }
            if (Objects.isNull(paasFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, MessageConstant.FORM_NOT_EXIST);
            }
//            saasAddHelp.handleFormEntity(paasFormEntityExt, formDataAddGetDTO.getSaasMark(), formDataAddGetDTO.getBusinessType());
            formDataAddGetVO.setPaasFormEntity(paasFormEntityExt);
            if (formDataAddGetDTO.getFormId() == null) {
                formDataAddGetDTO.setFormId(paasFormEntityExt.getId());
            }
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }

            // 获取字段解释信息，并且过滤不可见字段 start
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataAddGetDTO, handlerExplainDTO, false);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
            HandlerExplainVO handlerExplainVO = formDataAddFormExplainHandlerName.handleExplain(handlerExplainDTO);
            if (handlerExplainVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            explainList = handlerExplainVO.getHeadList();
            if (sheetFlag) {
                //处理各种类型回/付款单的字段，不能用回/付款单本身的解释，要根据不同类型回/付款单进行渲染
                fundHelp.handlePaymentSheet(true, sheetTypeEnum, explainList, corpid, paasFormEntityExt.getDistributorMark());
                fundHelp.setBySheetType(paasFormEntityExt, sheetTypeEnum);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                // 经销商名称和电话判重设置
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    paasFormDataService.handlerCustomerRepeat(corpid, formId, explainList, businessType);
                }
                //处理账期
                fundSetService.formatPeriod(corpid, businessType, formId, explainList);
            }
            // 流水号设置
            String serialNo = "";
            for ( FieldAttrEntity fieldAttrEntity : explainList ) {
                // 获取流水号
                if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.SERIALNO.getType()) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ZERO)) {
                    serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
                }
                // fix:18442 【移动端、web端】新建、编辑页面，不展示系统自动生成字段
                if ( Objects.equals(fieldAttrEntity.getUnableEditMemo(), I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD)) ) {
                    fieldAttrEntity.setVisible(0);
                }
                if (FieldTypeEnum.SELECT_PRODUCT.getType().equals(fieldAttrEntity.getFieldType())) {
                    DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
                    if (Objects.nonNull(defaultAttr)) {
                        String defaultType = defaultAttr.getDefaultType();
                        if (DefaultTypeEnum.PRODUCT_DATA_RELY.getAlias().equals(defaultType)) {
                            List<RelyPoJo> relyPoJoList = paasFormExplainService.selectProductRely(formDataAddGetDTO.getCorpid(), formDataAddGetDTO.getFormId());
                            fieldAttrEntity.setRelyList(relyPoJoList);
                        }
                    }
                }
            }
            formDataAddGetVO.setSerialNo(serialNo);
            proDetailHandlerHelp.handelSaasSpecialItem(explainList, businessType, formDataAddGetDTO.getSubBusinessType(),
                    formDataAddGetDTO.getDifferenceBusinessType(), formDataAddGetDTO.getDistributorMark());
            // 设置默认的关联数据
            paasFormHelp.setDefaultLinkData(explainList, formDataAddGetDTO, handlerExplainVO);
            // 获取字段解释信息，并且过滤不可见字段 end

            // 新建表单时SaaS某些字段赋初始值
            if (Objects.equals(formDataAddGetDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                for (FieldAttrEntity item : explainList) {
                    // 新建、编辑页面，不展示系统自动生成字段
                    if (Objects.equals(item.getUnableEditMemo(), I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD))) {
                        item.setVisible(0);
                    }
                }
                if (formDataAddGetDTO.getSaasSpecialParamPojo() != null) {
                    String phoneNum = formDataAddGetDTO.getSaasSpecialParamPojo().getPhoneNum();
                    for (FieldAttrEntity item : explainList) {
                        // 各个业务场景，只有一个号码新建，直接break
                        if (Objects.equals(item.getAttr(), CustomerManagementEnum.PHONE.getAttr())) {
                            if (phoneNum != null) {
                                JSONArray phoneArray = new JSONArray();
                                JSONObject phoneObject = new JSONObject();
                                phoneObject.put(StringConstant.PHONE_TYPE_ATTR, "1");
                                phoneObject.put(StringConstant.PHONE_TEL_ATTR, phoneNum);
                                phoneArray.add(phoneObject);
                                item.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(phoneArray));
                                break;
                            }
                        }
                    }
                }
                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(formDataAddGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(explainList);
                if (Objects.nonNull(formDataAddGetDTO.getSaasSpecialParamPojo())) {
                    formatExplainDTO.setLinkBusinessType(formDataAddGetDTO.getSaasSpecialParamPojo().getLinkBusinessType());
                }

                distributorAddHelp.formatExplain(formatExplainDTO);
                formDataAddGetVO.setExplainList(formatExplainDTO.getExplainList());
            }

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("DistributorFormDataServiceImpl.addGet DistributorFrom 数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataAddGetVO;
    }

     @Override
     @Transactional(rollbackFor = Exception.class)
     public FormDataAddVO add(FormDataAddDTO formDataSaveDTO) throws XbbException {
         FormDataAddVO formDataSaveVO = new FormDataAddVO();
         Integer isImport = formDataSaveDTO.getIsImport();
         String corpid = formDataSaveDTO.getCorpid();
//         if(Objects.equals(formDataSaveDTO.getBusinessType(),XbbRefTypeEnum.RED_RECEIVABLES.getCode())){
//             formDataSaveDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
//         }
         Integer businessType = formDataSaveDTO.getBusinessType();

         try {
            /*
              预收/付款余额表单逻辑处理，把formDataSaveDTO内的参数都置为预收/付款单类型
              如果得到为null，说明不是预收/付款；
              如果得到非null form，说明已经对预收/付款单处理完毕，即读取到了回款单的form
              如果回款单form不存在，则throw
             */
             PaasFormEntityExt paasFormEntityExt = proFormHelp.prePaymentHandle(formDataSaveDTO);
             if (Objects.isNull(paasFormEntityExt)) {
                 paasFormEntityExt = paasFormModel.getByKey(formDataSaveDTO.getFormId(), formDataSaveDTO.getCorpid());
             }
             if ( paasFormEntityExt == null ) {
                 throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
             }
             PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formDataSaveDTO.getFormId(), corpid);
             if ( Objects.isNull(paasFormExplainEntity) ) {
                 throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
             }
             //报价单新版本跳过新建权限校验
             JSONObject data = formDataSaveDTO.getDataList();
             // 新建权限校验
             if (!Objects.equals(isImport, 1) && !Objects.equals(1, formDataSaveDTO.getIsBusinessRule()) && !PlatFormEnum.INTERNAL.getValue().equals(formDataSaveDTO.getPlatform())) {
                 VerifyAddPermissionDTO verifyAddPermissionDTO = new VerifyAddPermissionDTO();
                 BeanUtil.copyProperties(formDataSaveDTO, verifyAddPermissionDTO);
                 verifyAddPermissionDTO.setMenuId(paasFormExplainEntity.getMenuId());
                 ProPermissionHelp.verifyAddPermission(verifyAddPermissionDTO);
             }
             Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
             // 判断是否开启了流程
             processFieldHelp.processSetVisible(paasFormEntityExt, explainMap);
             // 流水号开启严控模式
             PaasFormDataEntity paasFormDataEntity = setSerialNo(formDataSaveDTO, corpid, businessType, explainMap);

             ValidateDataDTO validateDataDTO = new ValidateDataDTO();
             BeanUtil.copyProperties(formDataSaveDTO, validateDataDTO);
             validateDataDTO.setData(data);
             validateDataDTO.setExplainMap(explainMap);
             validateDataDTO.setOwnerIds(formDataSaveDTO.getOwnerId());
             //发票、回款单金额明细处理
             SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
             boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
             JSONArray amountDetail = saasSaveHelper.getAmountDetail4Check(null, sheetTypeEnum, data,businessType);
             formDataSaveDTO.setAmountDetail(amountDetail);
             validateDataDTO.setAmountDetail(amountDetail);
             try {
                 // 字段校验
                 ProSaveHelp.analyticalData(validateDataDTO);
             } catch (Exception e) {
                 LOG.error("ProSaveHelp.beforeSave出错", e);
                 throw new XbbException(SystemErrorCodeEnum.API_ERROR_100129);
             }
             formDataSaveDTO.setCoUserId(validateDataDTO.getCoUserId());
//             setSpecialParam(formDataSaveDTO, validateDataDTO);
             formDataValidateDataHelp.validateData(validateDataDTO);
             // 分type检验
             distributorSaveHelp.beforeSave(validateDataDTO);
             // 产品可见人和可见部门
//             if ( Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) ) {
//                 formDataSaveDTO.setVisbleDept(validateDataDTO.getVisbleDept());
//                 formDataSaveDTO.setVisbleUser(validateDataDTO.getVisbleUser());
//             }
             // 设置subBusinessType
             if ( validateDataDTO.getSubBusinessType() != null ) {
                 formDataSaveDTO.setSubBusinessType(validateDataDTO.getSubBusinessType());
             }
             //设置默认值 防止自定义图表分组统计不准确
//            saasSaveHelp.initDefaultValue(validateDataDTO);
             //审批内明细处理
             if ( CollectionsUtil.isNotEmpty(amountDetail) ) {
                 SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = validateDataDTO.getSaasNeedRedundantAttrPoJo();
                 saasNeedRedundantAttrPoJo.setAmountDetail(amountDetail);
             }
             formDataSaveDTO.setSaasNeedRedundantAttrPoJo(validateDataDTO.getSaasNeedRedundantAttrPoJo());
             BeanUtil.copyProperties(formDataSaveDTO, paasFormDataEntity);
             String ownerId = formDataSaveDTO.getUserId();
             paasFormDataEntity.setOwnerId(ownerId);
             // 所属部门的id，由前端传入 所属部门不可见，前端拿不到时，卡特建议直接赋值-1
             Long departmentId = validateDataDTO.getDepartmentId() == null ? -1L : validateDataDTO.getDepartmentId();
             paasFormDataEntity.setDepartmentId(departmentId);
             formDataSaveDTO.setDepartmentId(departmentId);
             if ( Objects.nonNull(formDataSaveDTO.getOwnerId()) && !formDataSaveDTO.getOwnerId().isEmpty() ) {
                 paasFormDataEntity.setOwnerId(Objects.toString(formDataSaveDTO.getOwnerId().get(0).getId(), ""));
             }
             paasFormDataEntity.setData(formDataSaveDTO.getDataList());
             paasFormDataEntity.setSerialNo(formDataSaveDTO.getSerialNo());
             paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
             paasFormDataEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
             paasFormDataEntity.setCreatorId(formDataSaveDTO.getUserId());
             if ( StringUtil.isNotEmpty(FastJsonHelper.getStringFromFormData(formDataSaveDTO.getDataList(), FieldTypeEnum.CREATORID.getAlias())) ) {
                 paasFormDataEntity.setCreatorId(FastJsonHelper.getStringFromFormData(formDataSaveDTO.getDataList(), FieldTypeEnum.CREATORID.getAlias()));
                 formDataSaveDTO.getDataList().remove(FieldTypeEnum.CREATORID.getAlias());
             }
             Long modelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
             paasFormDataEntity.setSysLong10(modelType == null ? ModelTypeEnum.PLAN.getCode() : modelType);
             // 是否往form_data表中插入数据
             Integer noApprovalRequired = 1;
             //如果是在线支付流水生成回款单也不进审批，直接进回款单主表
             if (paasFormEntityExt.getIsProcessForm().equals(1) && !Objects.equals(formDataSaveDTO.getIsImport(), 1)
                     && !Objects.equals(1, formDataSaveDTO.getIsBusinessRule()) && Objects.isNull(formDataSaveDTO.getOnlinePaymentFlowEntity())) {
                 StartProcessDTO startProcessDTO = new StartProcessDTO();
                 BeanUtil.copyProperties(formDataSaveDTO, startProcessDTO);
                 if (sheetFlag) {
                     startProcessDTO.setBusinessType(sheetTypeEnum.getXbbRefTypeEnum().getCode());
                 }
                 startProcessDTO.setOwnerId(paasFormDataEntity.getOwnerId());
                 startProcessDTO.setCreatorId(paasFormDataEntity.getCreatorId());
                 startProcessDTO.setData(formDataSaveDTO.getDataList());
//                 startProcessDTO.setModelType(modelType);
                 // app首页常用表单进入的menuId不对
                 if ( Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                     PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataSaveDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
                     startProcessDTO.setMenuId(paasFormEntity.getMenuId());
                 } else if ( Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) ) {
                     PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), formDataSaveDTO.getCorpid());
                     startProcessDTO.setMenuId(paasFormEntity.getMenuId());
                 }
//                 if (XbbRefTypeEnum.postPositionBusinessType(businessType, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
//                     if (postPositionProcessHelp.isAutoReject(startProcessDTO)) {
//                         throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
//                     }
//                 } else {
                     StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, null);
                     if ( Objects.isNull(startProcessVO) ) {
                         throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
                     }
                     noApprovalRequired = startProcessVO.getNoApprovalRequired();
//                 }
             }

             if (noApprovalRequired.equals(1) ) {
                 // 保存区分
                 formDataSaveDTO.setExplainMap(explainMap);
                 Object richTextData = FormDataUtil.removeRichText(paasFormDataEntity.getData());
                 //插入表单数据
                 AfterSaveVO afterSaveVO = distributorProModelService.insert(formDataSaveDTO, paasFormDataEntity, paasFormEntityExt);
                 //插入富文本数据
                 richTextService.saveFormRichText(formDataSaveDTO, paasFormDataEntity, richTextData);
                 if(Objects.nonNull(afterSaveVO.getSpecialMsg())){
                     formDataSaveVO.setSpecialMsg(afterSaveVO.getSpecialMsg());
                 }
                 formDataSaveVO.setDataId(afterSaveVO.getFormDataId());
                 String businessRules = paasFormEntityExt.getBusinessRules();
                 if (!Objects.equals(1, formDataSaveDTO.getIsBusinessRule()) && Objects.equals("1", businessRules)) {
                     ActiveRuleDTO activeRuleDTO = new ActiveRuleDTO();
                     BeanUtil.copyProperties(formDataSaveDTO, activeRuleDTO);
                     activeRuleDTO.setDataId(paasFormDataEntity.getId());
                     long now = DateUtil.getInt();
                     paasFormDataEntity.setAddTime(now);
                     paasFormDataEntity.setUpdateTime(now);
                     PaasFormDataEntity newFormData = distributorProModelService.getFormDataEntity(corpid, formDataSaveDTO.getSaasMark(),formDataSaveDTO.getBusinessType(), afterSaveVO.getFormDataId());
                     IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(formDataSaveDTO.getCorpid(), formDataSaveDTO.getBusinessType(), formDataSaveDTO.getSaasMark());
                     paasFormSubDataModel.transferSubForm(newFormData, indexTypeEnum);
                     activeRuleDTO.setPaasFormDataEntity(newFormData);
                     activeRuleDTO.setExplainList(JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class));
                     formDataActiveRuleHelp.activeRule(activeRuleDTO);
                 }
                 if ( Objects.equals(afterSaveVO.getCode(), PaasConstant.FORM_ADD_PROCESS_RETURN_CODE) ) {
                     formDataSaveVO.setMsg(afterSaveVO.getMsg());
                     formDataSaveVO.setCode(afterSaveVO.getCode());
                 } else {
                     formDataSaveVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                     formDataSaveVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                 }
             } else {
                 formDataSaveVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                 formDataSaveVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
             }
             formDataSaveVO.setFormDataId(paasFormDataEntity.getId());

         } catch (XbbException e) {
             throw e;
         } catch (Exception e) {
             LOG.error("paasFormData数据库保存表单数据出错", e);
             throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
         }
         return formDataSaveVO;
     }

    /**
     * 开启严控后流水号生成
     * @param formDataSaveDTO
     * @param corpid
     * @param businessType
     * @param explainMap
     * @return
     * @throws XbbException
     */
    private PaasFormDataEntity setSerialNo(FormDataAddDTO formDataSaveDTO, String corpid, Integer businessType, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        Integer isImport = formDataSaveDTO.getIsImport();
        FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.SERIALNO.getAlias());
        // 报价单新版本导入不需要改变流水号
        Boolean flag = true;
        if (Objects.equals(isImport, BasicConstant.ONE) && Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && Objects.nonNull(formDataSaveDTO.getGroupNumber())){
            Integer version = Integer.parseInt(formDataSaveDTO.getSerialNo().substring(formDataSaveDTO.getGroupNumber().length(), formDataSaveDTO.getGroupNumber().length()+1));
            if (!Objects.equals(version, BasicConstant.ONE)){
                flag =false;
            }
        }
        if (isToCreateSerialNo(formDataSaveDTO, businessType, fieldAttrEntity) && flag) {
            getSerialNo(formDataSaveDTO, corpid, fieldAttrEntity);
            JSONObject dataList = formDataSaveDTO.getDataList();
            if ( Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) ) {
                // 报价单编号是组号加版本号
                formDataSaveDTO.setGroupNumber(formDataSaveDTO.getSerialNo());
                String quotationSerialNo = formDataSaveDTO.getSerialNo() + StringConstant.DEFAULT_VERSION;
                dataList.put(QuotationEnum.VERSION.getAttr(), StringConstant.DEFAULT_VERSION);
                dataList.put(QuotationEnum.QUOTATION_NO.getAttr(), quotationSerialNo);
                dataList.put(QuotationEnum.GROUP_NUMBER.getAttr(), formDataSaveDTO.getGroupNumber());
                paasFormDataEntity.setData(dataList);
                formDataSaveDTO.setSerialNo(quotationSerialNo);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())){
                dataList.put(FieldTypeEnum.SERIALNO.getAlias(), formDataSaveDTO.getSerialNo());
                paasFormDataEntity.setSerialNo(formDataSaveDTO.getSerialNo());
                paasFormDataEntity.setData(dataList);
                // 规格字段是否启用
                FieldAttrEntity speification = explainMap.get(ProductEnum.SPECIFICATION.getAttr());
                if (Objects.equals(speification.getIsOpen(), BasicConstant.ONE)) {
                    Object o1 = dataList.get(ProductEnum.SPECIFICATION.getAttr());
                    if (!Objects.equals(isImport, BasicConstant.ONE)) {
                        LinkedHashMap map = (LinkedHashMap) o1;
                        Integer num = 0;
                        if (Objects.nonNull(map)) {
                            ArrayList specDetails = (ArrayList) map.get("specDetails");
                            for (Object specDetail : specDetails) {
                                LinkedHashMap specDetail1 = (LinkedHashMap) specDetail;
                                specDetail1.put("specCode", formDataSaveDTO.getSerialNo() + "." + num);
                                num++;
                            }
                        }
                    } else {
                        JSONObject map = (JSONObject) o1;
                        Integer num = 0;
                        if (Objects.nonNull(map)) {
                            JSONArray specDetails = (JSONArray) map.get("specDetails");
                            for (Object specDetail : specDetails) {
                                JSONObject specDetail1 = (JSONObject) specDetail;
                                specDetail1.put("specCode", formDataSaveDTO.getSerialNo() + "." + num);
                                num++;
                            }
                        }
                    }
                }
            }else {
                dataList.put(FieldTypeEnum.SERIALNO.getAlias(),formDataSaveDTO.getSerialNo());
                paasFormDataEntity.setData(dataList);
                paasFormDataEntity.setSerialNo(formDataSaveDTO.getSerialNo());
            }
        }
        return paasFormDataEntity;
    }

    /**
     * 判断是否去生成流水号
     * @param formDataSaveDTO
     * @param businessType
     * @param fieldAttrEntity
     * @return
     */
    private boolean isToCreateSerialNo(FormDataAddDTO formDataSaveDTO, Integer businessType, FieldAttrEntity fieldAttrEntity) {
        return Objects.nonNull(fieldAttrEntity)
                // 报价单
                && (((StringUtil.isEmpty(formDataSaveDTO.getGroupNumber()) && Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && !Objects.equals(formDataSaveDTO.getIsImport(), BasicConstant.ONE ))
                // 其他特殊流水号 红冲销项发票 红冲进项发票
                || (StringUtil.isEmpty(formDataSaveDTO.getSerialNo())&& !Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && !Objects.equals(formDataSaveDTO.getIsImport(), BasicConstant.ONE ) ))
                // 导入
                || ( Objects.equals(formDataSaveDTO.getIsImport(), BasicConstant.ONE ) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)))
                ;

    }

    /**
     * 开启严控模式后，生成相应的流水号
     * @param formDataSaveDTO
     * @param corpid
     * @param fieldAttrEntity
     * @throws XbbException
     */
    private void getSerialNo(FormDataAddDTO formDataSaveDTO, String corpid, FieldAttrEntity fieldAttrEntity) throws XbbException {
        if (Objects.nonNull(fieldAttrEntity)){
            if (Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)){
                // 校验流水号是否重复
                //Boolean flag = false;
                //while (!flag){
                    String serialNo = saasSaveHelp.getSerialNo(corpid, formDataSaveDTO.getFormId(), fieldAttrEntity);
                    formDataSaveDTO.setSerialNo(serialNo);
                    // 校验流水号是否重复
                    FormDataRepeatDTO formDataRepeatDTO = new FormDataRepeatDTO();
                    BeanUtil.copyProperties(formDataSaveDTO,formDataRepeatDTO);
                    formDataRepeatDTO.setSerialNo(serialNo);
                    formDataRepeatDTO.setValue(serialNo);
                    //flag = repeat(formDataRepeatDTO).getNoRepeat();
                //}
            }
        }
    }

    @Override
    public void batchAddContact(List<ValidateDataDTO> validateDataDTOS, Long customerId, UserVO userVO , String attr, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {

        if (Objects.nonNull(validateDataDTOS) && !validateDataDTOS.isEmpty() && !Objects.equals(validateDataDTOS.get(0).getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(userVO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, validateDataDTOS.size(), xbbRefTypeEnum,
                    validateDataDTOS.get(0).getFormId());
            Integer allStatus = packageStatusHelp.getPackageStatus(userVO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, validateDataDTOS.size());
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }

        for ( ValidateDataDTO validateDataDTO : validateDataDTOS ) {
            if (Objects.isNull(validateDataDTO.getSerialNo())){
                validateDataDTO.setSerialNo("");
            }
            JSONObject data = validateDataDTO.getData();
            if ( data.isEmpty() ) {
                continue;
            }
            // 把关联客户id塞进去
            data.put(attr, customerId);
            FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
            BeanUtil.copyProperties(validateDataDTO, formDataAddDTO);
            formDataAddDTO.setLoginUser(userVO);
            formDataAddDTO.setDataList(data);
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(formDataAddDTO, paasFormDataEntity);
            String ownerId = formDataAddDTO.getUserId();
            if ( Objects.nonNull(formDataAddDTO.getOwnerId()) && !formDataAddDTO.getOwnerId().isEmpty() ) {
                paasFormDataEntity.setOwnerId(formDataAddDTO.getOwnerId().get(0).getId().toString());
            }
            paasFormDataEntity.setOwnerId(ownerId);

            paasFormDataEntity.setData(formDataAddDTO.getDataList());
            // 所属部门的id，由前端传入
            paasFormDataEntity.setDepartmentId(formDataAddDTO.getDepartmentId());
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
            if ( paasFormEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
            paasFormDataEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            if ( validateDataDTO.getProcessCreatorId() == null ) {
                paasFormDataEntity.setCreatorId(formDataAddDTO.getUserId());
            } else {
                paasFormDataEntity.setCreatorId(validateDataDTO.getProcessCreatorId());
            }
            PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(validateDataDTO.getFormId(), validateDataDTO.getCorpid());
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
            // 流水号开启严控模式
            FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.SERIALNO.getAlias());
            if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)) {
                FormDataAddDTO formDataSaveDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataSaveDTO);
                formDataSaveDTO.setFormId(formDataAddDTO.getFormId());
                getSerialNo(formDataSaveDTO, validateDataDTO.getCorpid(), fieldAttrEntity);
                paasFormDataEntity.setSerialNo(formDataSaveDTO.getSerialNo());
                formDataAddDTO.getDataList().put(FieldTypeEnum.SERIALNO.getAlias(),formDataSaveDTO.getSerialNo());
                formDataAddDTO.setSerialNo(formDataSaveDTO.getSerialNo());
            }
            // 是否往form_data表中插入数据
            Integer noApprovalRequired = 1;
            if(Objects.equals(paasFormEntityExt.getIsProcessForm(), 1) && !Objects.equals(validateDataDTO.getIsImport(),1)){
                StartProcessDTO startProcessDTO = new StartProcessDTO();
                BeanUtil.copyProperties(formDataAddDTO, startProcessDTO);
                startProcessDTO.setFormId(paasFormEntityExt.getId());
                startProcessDTO.setData(formDataAddDTO.getDataList());
                startProcessDTO.setFormDataId(0L);
                startProcessDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                startProcessDTO.setBusinessType(xbbRefTypeEnum.getCode());
                startProcessDTO.setCreatorId(paasFormDataEntity.getCreatorId());
                // Long modelType = fundSetService.getModelType(formDataAddDTO.getCorpid(),XbbRefTypeEnum.CRM);
                // startProcessDTO.setModelType(modelType == null ? BasicConstant.ONE : modelType);
                StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, null);
                if (Objects.isNull(startProcessVO)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
                }
                noApprovalRequired = startProcessVO.getNoApprovalRequired();
            }
            if ( noApprovalRequired.equals(1) ) {
                //保存区分
                distributorProModelService.insert(formDataAddDTO, paasFormDataEntity, paasFormEntityExt);
            }
        }
    }

}
